package com.dyna.demo.common;

import cn.hutool.core.util.StrUtil;
import com.dyna.callback.Callback;
import com.dyna.constants.StringPool;
import com.dyna.core.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Map;

@Slf4j
@Service
public class CommonService {

    @Value("${dyna.file.path}")
    private String filePath;

    /**
     * continue和break的区别
     */
    public Boolean forLoop() {
        for (int i = 0; i < 10; i++) {
            if (3 == i) {
                // 如果等于3则跳过本次循环
                continue;
            }
            if (6 == i) {
                // 如果等于6则跳出循环
                break;
            }
            log.info("输出循环结果:::{}", i);
        }
        return Boolean.TRUE;
    }

    public Boolean whileLoop() {
        this.testWhile();
        return Boolean.TRUE;
    }

    /**
     * doWhile虽然不符合条件，但是还是会执行一次
     */
    private void doWhile() {
        int i = 8;
        do {
            log.info("执行啦...");
            i++;
        }while (i < 7);
    }

    /**
     * 常用while
     */
    private void testWhile() {
        int i = 0;
        while (i < 10) {
            if (3 == i) {
                // 如果等于3则跳过本次循环
                log.info("跳出了本次循环");
                i++;
                continue;
            }
            if (6 == i) {
                // 如果等于6则跳出循环
                log.info("结束了循环");
                break;
            }
            log.info("while=={}循环执行了...", i);
            i++;
        }
    }

    public Boolean createCsvDataFile(Map<String, String> map) {
        String data = map.get("data");
        String[] split = data.split(StringPool.HASH);

        File file = new File(filePath + map.get("fileName"));
        StringBuilder stringBuffer = new StringBuilder();
        try {
            boolean exists = file.exists();
            if (!exists) {
                boolean newFile = file.createNewFile();
                log.info("创建新文件结果:::{}", newFile);
            }
            String readData = FileUtil.readToString(file);
            if (StrUtil.isNotBlank(readData)) {
                for (String line : split) {
                    stringBuffer.append(StringPool.NEWLINE).append(line);
                }
            }else {
                stringBuffer.append(data);
            }
            FileUtil.writeToFile(file, stringBuffer.toString(), Boolean.TRUE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Boolean.TRUE;
    }

    public Boolean callback() {
        this.computeRate(() -> log.info("执行且输出的内容为aaaa"));
        log.info("n年后");
        this.computeRate(() -> log.info("执行且输出的内容为bbbb"));
        return Boolean.TRUE;
    }

    private void computeRate(Callback callBack) {
        log.info("前半部分相同代码");
        callBack.call();
        log.info("后半部分相同代码");
    }


}
